package com.lukk.service.realm;

import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lukk.constant.Const;
import com.lukk.dao.InternalWorkerDAO;
import com.lukk.pojo.InternalWorker;
import com.lukk.util.AESUtils;
import com.lukk.util.MD5Utils;

/**
 * 
 * MyRealm.java 2016-7-9
 * 
 * Copyright zhaocj Inc. All rights reserved. Love Me Like Love Justin Bieber
 */
@Service
public class MyRealm extends AuthorizingRealm {
	private static Logger logger = LogManager.getLogger(MyRealm.class.getName());
	@Autowired
	private InternalWorkerDAO internalWorkerDAO;

	public InternalWorkerDAO getInternalWorkerDAO() {
		return internalWorkerDAO;
	}

	public void setInternalWorkerDAO(InternalWorkerDAO internalWorkerDAO) {
		this.internalWorkerDAO = internalWorkerDAO;
	}

	/**
	 * 获取授权信息
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		return null;
	}

	/**
	 * 获取身份验证相关信息
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
			throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
		InternalWorker internalWorker = null;
		try {
			logger.debug("=================================开启认证=======================================");
			Map<String, Object> queryMap = new HashMap<String, Object>();
			queryMap.put("id", null);
			queryMap.put("workerCode", token.getUsername());
			internalWorker = internalWorkerDAO.selectByPrimaryKey(queryMap);
			if (internalWorker != null) {
				String saltStr = AESUtils.aesDecrypt(internalWorker.getSalt(),
						AESUtils.SALTKEY);
				
				String codePassword = MD5Utils.GetSaltCode(
						String.valueOf(token.getPassword()), saltStr);
				logger.debug("登陆密码：{}，数据库密码：{}", token.getPassword(), internalWorker.getPassword());
				if (codePassword.equals(internalWorker.getPassword())) {
					SecurityUtils.getSubject().getSession().setAttribute(Const.SESSION_USER, internalWorker);
					return new SimpleAuthenticationInfo(internalWorker.getWorkerCode(),
							String.valueOf(token.getPassword()), getName());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}